package com.bsoft.exchange.service;

import com.bsoft.exchange.util.Dom4jUtil;
import com.bsoft.exchange.util.ParamXmlUtils;
import com.google.gson.Gson;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.StandardCharsets;

@Service
public class DetectService {

    private Gson gson = new Gson();

    /**
     * 核酸检测开单
     * @param patientId 病人id
     * @param date 预约时间
     * @return
     */
    public String insertDetect(String patientId, String date) {
        OutputStream out = null;
        InputStream input = null;
        String code = null;
        try {
            HttpURLConnection httpURLConnection = getHttpURLConnection("http://192.168.160.218:9010/wx?wsdl");
            String requestBody = ParamXmlUtils.format(ParamXmlUtils.detectParam(patientId, date), "sp_hsjc_insert");
            out = httpURLConnection.getOutputStream();
            out.write(requestBody.getBytes());
            int statusCode = httpURLConnection.getResponseCode();
            if (statusCode == 200) {
                input = httpURLConnection.getInputStream();
                byte[] b = new byte[1024];
                StringBuilder result = new StringBuilder();
                int length = 0;
                while ((length = input.read(b)) != -1) {
                    String str = new String(b, 0, length, StandardCharsets.UTF_8);
                    result.append(str);
                }
                String xml = Dom4jUtil.xmlToStr(result.toString());
                if (StringUtils.isNoneBlank(xml)) {
                    code = Dom4jUtil.getNodeValue(xml, "vl_code");
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            releaseResources(out, input);
        }
        return code;
    }

    private HttpURLConnection getHttpURLConnection(String url) throws IOException {
        URL url1 = new URL(url);
        URLConnection urlConnection = url1.openConnection();
        HttpURLConnection httpURLConnection = (HttpURLConnection) urlConnection;
        httpURLConnection.setDoInput(true);
        httpURLConnection.setDoOutput(true);
        httpURLConnection.setRequestMethod("POST");
        httpURLConnection.setRequestProperty("content-type", "text/xml;charset=UTF-8");
        return httpURLConnection;
    }

    private void releaseResources(OutputStream out, InputStream input) {
        if (out != null) {
            try {
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (input != null) {
            try {
                input.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
